
class TangrenjieSearch extends AbstractPlugin {

  static BASE_URL = 'https://www.trjvod.com';

  async fetchSearchResults(query) {
    const searchUrl = `${TangrenjieSearch.BASE_URL}/vod/search.html?wd=${encodeURIComponent(query)}`;
    const http_headers = {
      'User-Agent': TangrenjieSearch.DEFAULT_USER_AGENT,
      'Origin': TangrenjieSearch.BASE_URL,
    };
    const result  = await doHttpRequestSync(searchUrl, { headers: http_headers });
    if(result.status !== 'success') {
      return null;
    }
    const data = result.body;

    const parser = new DOMParser();
    const doc = parser.parseFromString(data, 'text/html');

    const searchResults = [];

    const items = doc.querySelectorAll('.vodlist .searchlist_item');
    items.forEach(item => {
      const searchResult = new SearchResult();
      searchResult.site_icon = '/plugins/tangrenjie/icon.png';
      searchResult.site_name = TangrenjieSearch.BASE_URL.replace(/https?:\/\/(www\.)?/, '');

      const imageElement = item.querySelector('.searchlist_img a');
      searchResult.image = imageElement ? imageElement.getAttribute("data-original").trim() : '';

      const titleElement = item.querySelector('.vodlist_title a');
      searchResult.title = titleElement ? titleElement.textContent.trim() : '';

      const href = titleElement ? titleElement.getAttribute('href') : '';
      searchResult.link = href.startsWith('/') ? `${TangrenjieSearch.BASE_URL}${href}` : href;

      const infoElements = item.querySelectorAll('.vodlist_sub');
      const infos = [];
      infoElements.forEach(infoElement => {
        const info = infoElement.textContent.trim();
        if(info) {
          infos.push(info);
        }
      })
      searchResult.description = infos.join('\n');

      searchResults.push(searchResult);
    });
    return searchResults;
  }

}
Registry.registerClass("TangrenjieSearch", new TangrenjieSearch());